/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sgsmcan.Utils;

import com.sgsmcan.Dao.PaginationDao;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.hibernate.criterion.DetachedCriteria;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

/**
 *
 * @author user
 */
public class Paginacion<T> extends LazyDataModel<T> implements Serializable{

    DetachedCriteria criteriaRowCount;
    DetachedCriteria criteriaList;
    DetachedCriteria criteriaAllList;
    PaginationDao<T> daoPaginacion;
    public Paginacion(DetachedCriteria criteria) {
        daoPaginacion = new PaginationDao();
        ensamblarCriteria(criteria);
    }
    
    private void ensamblarCriteria(DetachedCriteria criteria){
        try {
            this.criteriaRowCount = copyDetachedCriteria(criteria);
            this.criteriaList = copyDetachedCriteria(criteria);
            this.criteriaAllList = copyDetachedCriteria(criteria);
        } catch (IOException ex) {
           Utilitario.LOG.error("Error en Paginacion IOException", ex);
        } catch (ClassNotFoundException ex) {
            Utilitario.LOG.error("Error en Paginacion ClassNotFountException", ex);
        }
    }
    
    @Override
    public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
        int totalRows = daoPaginacion.getTotalRows(criteriaRowCount);
        this.setRowCount(totalRows);
        return daoPaginacion.getList(criteriaList, first, pageSize);
    }
    
    public List<T> getAllList(){
        return daoPaginacion.getAllList(criteriaAllList);
    }
    
    private DetachedCriteria copyDetachedCriteria(DetachedCriteria detachedCriteria) throws IOException, ClassNotFoundException {
        try {
            ByteArrayOutputStream baostream = new ByteArrayOutputStream();
            ObjectOutputStream oostream = new ObjectOutputStream(baostream);
            oostream.writeObject(detachedCriteria);
            oostream.flush();
            oostream.close();
            ByteArrayInputStream baistream = new ByteArrayInputStream(baostream.toByteArray());
            ObjectInputStream oistream = new ObjectInputStream(baistream);
            DetachedCriteria copy = (DetachedCriteria) oistream.readObject();
            oistream.close();
            return copy;
        } catch (IOException e) {
            throw e;
        } catch (ClassNotFoundException e) {
            throw e;
        }
    }
    
    
}
